<template>
  <view class="ts-part">
    <!-- 底部按钮部分 -->
    <view class="btnBox" v-if="requestEnd">
      <view class="text-tip-block" v-if="tsInfo.selectionEnabled && specialStatus == 2">
        <view class="text-tip" v-if="checkStaus == 1">
          本次登记将在
          <u-count-down color='#b0b0b0' separator-color='#b0b0b0' :timestamp="checkTime" :show-days="true"
            :show-hours="true" separator="zh" font-size='28'></u-count-down>
          截止
        </view>
        <view class="text-tip" v-else-if="checkStaus == 2">
          登记结果将在
          <u-count-down color='#b0b0b0' separator-color='#b0b0b0' :timestamp="proTime" :show-days="true"
            :show-hours="true" separator="zh" font-size='28'></u-count-down>
          后公布
        </view>
        <view class="text-tip" v-else>
          {{textTip}}
        </view>
      </view>
      <view class="left-icon " :class="fastTabCopy.length !== 1?'':'short'">
        <view class="icon-item" v-for="(item, tabIndex) in fastTabCopy" :key="tabIndex"
          @click="fastTabClick(item, tabIndex)">
          <view class="icon-image">
            <image :src="item.isAct ? item.actIcon : item.icon" mode="widthFix" :style="{'width':item.iconWidth}">
            </image>
          </view>
          <text v-if="cartNum !== 0 && item.title == '购物车'" class="number">{{ cartNum }}</text>
          <view class="left-icon-title">{{ item.title }}</view>
        </view>
      </view>
      <button class="btn_sell_Out" v-if="specialStatus == 1">商品尚未开售</button>
      <view class="bottom-content-box" v-else-if="specialStatus == 2">
        <view class="right-btn "
          v-if="(btnStatus == 1  && !tsInfo.selectionEnabled) || (btnStatus == 1 && tsInfo.selectionEnabled && checkStaus == 3 )">
          <button class="btn_sell_Out"> 商品已售罄</button>
        </view>
        <view class="right-btn "
          v-else-if="(btnStatus == 4 && !tsInfo.selectionEnabled) || (btnStatus == 1 && tsInfo.selectionEnabled && checkStaus == 3 )">
          <button class="btn_sell_Out"> 商品已下架</button>
        </view>
        <view class="right-btn" v-else>
          <!-- 开启登记获取购买资格 -->
          <view class="check-btnStyle" v-if="tsInfo.selectionEnabled">
            <button class="btn1 font32 " :class="(checkStaus == 2 || checkStaus== 4)? 'btn_sell_Out':''"
              @click='handleBtn(checkBtnText)'>{{checkBtnText}}</button>
          </view>
          <view class="normal-btnStyle" v-else>
            <button class="btn1" @click.stop="chooseBoxShow(true)" data-type="buynow">加入购物车</button>
            <button class="btn2 act" @click.stop="chooseBoxShow(true)" data-type="buynow">立即购买</button>
          </view>

        </view>
      </view>
      <button class="right-btn btn_sell_Out" v-else-if="specialStatus == 3">{{btnText}}</button>
      <button class="right-btn btn_sell_Out" v-else>活动已结束</button>
    </view>


    <view class="mask-box" v-if='boxShow' @touchmove.stop.prevent catchtouchmove="true" @click.stop="chooseBoxclose">
      <view class="parameter-box flex-box" @click.stop="stopClick">
        <view class="mask-main">
          <view class="parameter-close" @click.stop="chooseBoxclose">×</view>
          <view class="parameter-info flex-box">
            <view class="info-left">
              <image :src="ccJsonInfo.skuBlockUrl"></image>
            </view>
            <view class="info-right flex-column" v-if="price > 0">
              <view class="parameter-price mb20"><text class="mark">¥</text>{{ filterChecked.moneyFormat(price, 2) }}
              </view>
              <view class="has-choose">已选{{'"' + ccJsonInfo.valueName + '"' }}</view>
            </view>
          </view>
          <view class="parameter-specifications flex-column">
            <view class="specifications-title">容量</view>
            <view class="flex-box">
              <view class="specifications-item" v-for="(speItem, speIndex) in colorPriceJson.colorList"
                :class="[colorIdx == speIndex ? 'act' : '']" :key="speIndex">
                {{ speItem }}
              </view>
            </view>
          </view>
          <view class="change-count-box flex-box">
            <view class="flex-box">
              <view class="title">购买数量</view>
              <view v-if="tsInfo.purchaseLimitLabel&&tsInfo.purchaseLimitDisplay" class="promotion-box">
                <view class="general-tag">
                  <span class="font-act-color">{{ tsInfo.purchaseLimitLabel }}</span>
                </view>
              </view>
            </view>
            <view class="num-change buy-num">
              <image class="jian-btn " :src="chooseQty === 1 ?  goodsOperateBtn.delDisable : goodsOperateBtn.delActive"
                @click.stop="jianBtnTap">
              </image>
              <view class="buy-number">{{chooseQty}}</view>
              <image class="jia-btn numjia "
                :src="(chooseQty >= tsInfo.availableQty || chooseQty >= ccJsonInfo.frontQty || specialStatus!==2  ) ?  goodsOperateBtn.addDisable :  goodsOperateBtn.addActive"
                @click.stop="jiaBtnTap">
              </image>
            </view>
          </view>
        </view>
        <view class="right-btn">
          <view class="btnBox">
            <button v-if="specialStatus == 1" class="btn_sell_Out font31">商品尚未开售</button>
            <button v-else-if="specialStatus == 2 && btnStatus == 1" class=" btn_sell_Out">商品已售罄</button>
            <button v-else-if="btnStatus == 4 && specialStatus == 2" class="btn_sell_Out">商品已下架</button>
            <view :class="!tsInfo.selectionEnabled?'has-btn-padding':'has-no-padding'" v-else-if="specialStatus == 2">
              <view class="mult-btn" v-if="!tsInfo.selectionEnabled">
                <button class="btn1" @click.stop="takeCart" data-type="buynow">加入购物车</button>
                <button class="btn2 act" @click.stop="buyItNow">立即购买</button>
              </view>
              <button v-else class="btn1" @click.stop="buyItNow">立即购买</button>
            </view>
            <button v-else-if="specialStatus == 3" class="btn_sell_Out font31">{{btnText}}</button>
            <button class="btn_sell_Out" v-else>活动已结束</button>
          </view>
        </view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>
<script module="filterChecked" lang="wxs" src="@/utils/filter.wxs"></script>
<script>
  import {
    SYSTEM_INFO,
    MERCHANT_INFO,
    USER_INFO,
    USER_SPECICAL_INFO,
    CUSTOMER_INFO,
    CART_KEY
  } from '@/utils/constant';
  import api from '@/api/api';
  import util from '@/utils/util';
  import {
    setFav
  } from '@/utils/commonActItems.js'
  export default {
    data() {
      return {
        specialStatus: 0, //1.尚未开售 2.立即购买
        btnText: '',
        requestEnd: false,
        boxShow: false,
        tsInfo: {},
        chooseQty: 1,
        colorIdx: 0,
        fastTabCopy: [],
        preStartTime: 0,
        startTime: 0,
        endTime: 0,
        promulgateTime: 0,
        checkinCloseTime: 0,
        checkBtnText: '',
        textTip: '',
        checkStaus: 0, // 1-立即登记 2-等待公布结果 3-立即购买 4-登记结束 5-回到首页
        checkTime: 0,
        proTime: 0,

      }
    },

    watch: {
      specialStatus(val) {
        if (val == 2 && this.tsInfo?.selectionEnabled) {
          this.fastTabCopy = this.fastTab.slice(1)
        } else {
          this.fastTabCopy = this.fastTab
        }
      },
      checkStaus(val) {
        // 1-立即登记 2-等待公布结果 3-立即购买 4-登记结束 5-回到首页
        if (val == 1) {
          this.checkBtnText = '立即登记'
        } else if (val == 2) {
          this.checkBtnText = '等待公布结果'
        } else if (val == 3) {
          this.checkBtnText = '立即购买'
        } else if (val == 4) {
          this.checkBtnText = '登记结束'
        } else if (val == 5) {
          this.checkBtnText = '回到首页'
        }
      }
    },
    props: {
      btnStatus: {
        type: Number
      },
      isSpecial: {
        type: Boolean // TRUE代表商品配置了特殊购买 ，活动结束后有标记就一直显示活动已结束
      },
      productSKU: {
        type: String
      },
      tsActId: {
        typeof: String
      },
      ccJsonInfo: {
        typeof: Object
      },
      colorPriceJson: {
        typeof: Object
      },
      price: {
        type: String
      },
      fastTab: {
        type: Array
      },
      cartNum: {
        type: Number
      },
      detail: {
        type: Object
      },
      valueId: {
        type: String,
      },
      goodsOperateBtn: {
        type: Object
      }
    },
    mounted() {
      let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
      if (!!this.tsActId && !!customerInfo.jwt) {
        // 从订单列表过来的,以订单列表的活动id查询的活动为准
        this.getTsBySku(this.tsActId)
      } else {
        this.getTsBySku()
      }
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      async getTsBySku(tsId) {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync('merchantInfo');
        let memberDetails = uni.getStorageSync('memberDetails');
        let query = {
          "store_id": merchantInfo.cloudMerchantStoreId,
          "sku_id": this.productSKU,
          "group_id": customerInfo.groupId,
          "member_level_id": memberDetails.memberLevelId,
          "merchant_id": merchantInfo.cloudMerchantId,
          'campaign_target_sale_id': tsId || ''
        }
        const result = await api.getTsBySku({
          header: {
            jwt: customerInfo.jwt
          },
          method: 'GET',
          query: query,
        });
        if (result.code == 1000) {
          let {
            teaserStartTime,
            campaignStartTime,
            campaignEndTime,
            promulgateTime,
            checkinCloseTime,
            campaignTargetSaleId,
            status
          } = result.data
          this.tsInfo = result.data
          this.preStartTime = util.formatTimeStamp(teaserStartTime)
          this.startTime = util.formatTimeStamp(campaignStartTime)
          this.endTime = util.formatTimeStamp(campaignEndTime)
          this.promulgateTime = util.formatTimeStamp(promulgateTime)
          this.checkinCloseTime = util.formatTimeStamp(checkinCloseTime)
          this.$emit('setTsInfo', result.data)
          if (status !== -2) {
            this.statusControl()
          } else {
            this.btnText = result.data.illegalNotice
            this.specialStatus = 3
            this.requestEnd = true
          }
        } else {
          if (result.data) {
            let {
              status,
              illegalNotice
            } = result.data
            if (status == -2) {
              this.specialStatus = 3
              this.btnText = illegalNotice
            } else {
              this.specialStatus = 4
            }
          } else {
            this.specialStatus = 4
          }
          this.requestEnd = true
        }
      },
      // 普通活动状态控制
      statusControl() {
        this.$commonFunction.getServerTime().then((nowTime) => {
          if (nowTime > this.preStartTime && nowTime < this.startTime) {
            this.specialStatus = 1
            if ((this.startTime - nowTime) < 86400000) {
              setTimeout(() => {
                this.specialStatus = 2
                if (this.tsInfo.selectionEnabled) {
                  // 抽签活动控制
                  this.checkStatusControl(nowTime)
                }
              }, (this.startTime - nowTime))
            }
          } else if (nowTime > this.startTime && nowTime < this.endTime) {
            this.specialStatus = 2
            // 登记状态
            if (this.tsInfo.selectionEnabled) {
              this.checkStatusControl(nowTime)
            }
            if ((this.endTime - nowTime) < 86400000) {
              setTimeout(() => {
                this.specialStatus = 4
              }, (this.endTime - nowTime))
            }
          } else {
            this.specialStatus = 4
          }
          this.requestEnd = true
        })
      },
      async fastTabClick(item) {
        if (item.title == '购物车') {
          uni.reLaunch({
            url: item.path,
          })
        } else {
          let operateType;
          if (item.isAct) {
            operateType = 'cancel'
            let params = {
              c_link_pagename: '商品详情页'
            }
            this.$parent.commonTrack('c_ebmp_wish_list_remove_from_wish_list', params)
          } else {
            this.$parent.commonTrack('c_ebmp_wish_list_add_to_wish_list', {
              c_link_pagename: '商品详情页'
            })
            operateType = 'add'

          }
          let res = await setFav(this.detail, operateType, this.valueId, 0)
          const {
            status,
            times
          } = res
          if (status) {
            this.fastTabCopy.map(item => {
              if (item.title == '喜欢' && operateType == 'add') {
                item.isAct = true
                if (times == 1) {
                  this.$parent.openFavModal()
                } else {
                  this.handleShowTextToast('添加成功')
                }
              } else if (item.title == '喜欢' && operateType == 'cancel') {
                item.isAct = false
                this.handleShowTextToast('已取消')
              }
            })
          }
        }
      },
      handleBtn(val) {
        if (val == '立即登记' && this.checkStaus == 1) {
          this.$parent.commonTrack('c_ebmp_target_sales_draws_register_to_draws', {})
          this.checkInTs()
        } else if (val == '回到首页') {
          this.$parent.commonTrack('c_ebmp_product_back_to_home_page', {})
          uni.reLaunch({
            url: '/pages/home/home'
          })
        } else if (val == '立即购买' && this.checkStaus == 3) {
          this.chooseBoxShow(true)
        }
      },
      // 登记
      async checkInTs() {
        let customerInfo = uni.getStorageSync(CUSTOMER_INFO);
        let merchantInfo = uni.getStorageSync('merchantInfo');
        const result = await api.checkInTs({
          header: {
            jwt: customerInfo.jwt
          },
          method: 'POST',
          query: {
            "storeId": merchantInfo.cloudMerchantStoreId,
            "skuId": this.productSKU,
            'campaignTargetSaleId': this.tsInfo.campaignTargetSaleId
          },
        });
        if (result.code === 1000) {
          this.getTsBySku(this.tsActId)
        }
      },
      checkStatusControl(nowTime) {
        let {
          isCheckin,
          selectionInfo,
          promulgateTime,
          checkinCloseTime
        } = this.tsInfo
        // checkStaus: 0, // 1-立即登记 2-等待公布结果 3-立即购买 4-登记结束 5-回到首页
        let status;
        if (nowTime < this.checkinCloseTime) {
          status = isCheckin ? 2 : 1
          let proTime = util.formatTimeStamp(promulgateTime) - nowTime
          this.proTime = proTime / 1000
          let checkTime = util.formatTimeStamp(checkinCloseTime) - nowTime
          this.checkTime = checkTime / 1000
          if (isCheckin) {
            this.timeOver(proTime, 1)
          } else {
            this.timeOver(checkTime)
          }

        } else if (nowTime > this.checkinCloseTime && nowTime < this.promulgateTime) {
          if (!isCheckin) {
            status = 4
            this.textTip = `本次登记已在${this.$parent.formatDate(checkinCloseTime)}结束，期待您下次参与`
          } else {
            let proTime = util.formatTimeStamp(promulgateTime) - nowTime
            this.proTime = proTime / 1000
            status = 2
            this.timeOver(proTime, 1)
          }
        } else if (nowTime > this.promulgateTime) {
          if (!isCheckin) {
            status = 4
            this.textTip = `本次登记已在${this.$parent.formatDate(checkinCloseTime)}结束，期待您下次参与`
          } else if (isCheckin && selectionInfo.selectionRecordStatus == 2) {
            status = 5
            this.textTip = '很遗憾，您未获取购买资格'
          } else if (isCheckin && selectionInfo.isLucky == 1) {
            this.textTip = '恭喜您获取购买资格'
            status = 3
          }
        }
        this.checkStaus = status
      },
      timeOver(cuttime, type) {
        if (cuttime < 86400000) {
          setTimeout(() => {
            if (!!type) {
              this.getTsBySku(this.tsActId)
            } else {
              this.statusControl()
            }
          }, cuttime);
        }
      },
      chooseBoxclose(val) {
        this.boxShow = false
        this.$commonSensors.popupEvent('PopupClick', {'popup_type' : '商品弹窗', 'popup_name': '半屏加购弹窗', 'button_name': '关闭'})
      },
      chooseBoxShow(val) {
        if (!this.tsInfo.selectionEnabled) {
          this.boxShow = val
          if(val) {
            this.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '商品弹窗', 'popup_name': '半屏加购弹窗'})
          }
        } else if (this.tsInfo.selectionEnabled && this.checkStaus == 3) {
          this.boxShow = val
          if(val) {
            this.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '商品弹窗', 'popup_name': '半屏加购弹窗'})
          }
        }
      },
      buyItNow: async function() {
        if (this.chooseQty > this.tsInfo.availableQty) {
          this.handleShowTextToast('已超出限购数量，详情请咨询顾问');
        } else {
          this.$parent.tianYuCheck(3)
        }
      },
      takeCart() {
        if (this.chooseQty > this.tsInfo.availableQty) {
          this.handleShowTextToast('已超出限购数量，详情请咨询顾问');
        } else {
          this.$parent.takeCart()
        }
      },
      stopClick() {
        return false
      },
      jianBtnTap() {
        if (this.specialStatus !== 2) {
          return
        }
        if (this.chooseQty > 1) {
          this.chooseQty--;
          this.$commonSensors.popupEvent('PopupClick', {'popup_type' : '商品弹窗', 'popup_name': '半屏加购弹窗', 'button_name': '减少'})
        } else {
          this.handleShowTextToast('购买数量低于购买范围')
        }
        this.$parent.setChooseQty(this.chooseQty)

      },
      jiaBtnTap() {
        //库存不足
        if (this.specialStatus !== 2) {
          return
        }
        if (this.ccJsonInfo.frontQty < 1) {
          this.handleShowTextToast('商品库存不足')
          return false
        }
        if (this.chooseQty === this.ccJsonInfo.frontQty) {
          this.handleShowTextToast('商品库存不足')
          return false;
        } else {
          if (this.chooseQty >= this.tsInfo.availableQty) {
            this.handleShowTextToast('已超出限购数量，详情请咨询顾问');
            return false;
          }
          this.chooseQty++;
          this.$commonSensors.popupEvent('PopupClick', {'popup_type' : '商品弹窗', 'popup_name': '半屏加购弹窗', 'button_name': '增加'})
        }
        this.$parent.setChooseQty(this.chooseQty)
        this.$parent.buyItNowTracking()
      },
      getTrackStatus() {
        let text = '';
        if (this.specialStatus == 1) {
          text = '商品尚未开售'
        } else if (this.specialStatus == 2 && this.tsInfo.selectionEnabled) {
          if (this.checkStaus == 1) {
            text = '已开始未登记'
          } else if (this.checkStaus == 4) {
            text = '登记结束'
          } else if (this.checkStaus == 2) {
            text = '等待公布结果'
          } else if (this.checkStaus == 3) {
            text = '已获取购买资格'
          } else if (this.checkStaus == 5 && this.tsInfo.isCheckin) {
            text = '未获取购买资格'
          }

        } else if (this.specialStatus == 4) {
          text = '活动已结束'
        }
        return text
      }
    }
  }
</script>

<style lang="scss">
  .font32 {
    font-size: 32rpx;
  }

  .left-icon {
    display: flex;
    width: 260rpx;

    &.short {
      width: 150rpx;
    }

    .icon-image {
      height: 60rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .icon-item {
      text-align: center;
      position: absolute;

      .number {
        position: absolute;
        right: 32rpx;
        top: 2rpx;
        color: #fff;
        width: 30rpx;
        height: 30rpx;
        line-height: 30rpx;
        padding: 0;
        border-radius: 100%;
        text-align: center;
        font-size: 20rpx;
        background-color: #CB171A;
      }
    }
  }

  .bottom-content-box {
    flex: 1;
    display: flex;

  }

  .right-btn {
    flex: 1;
    display: flex;
    justify-content: center;

    .normal-btnStyle,
    .check-btnStyle {
      flex: 1;
      display: flex;
    }

    button {
      // flex: 1;
	  width: 232rpx;
    }

    .has-no-padding {
      width: 100%;

      button {
        flex: 1;
      }
    }

    .has-btn-padding {
      padding: 0 40rpx;
      width: 100%;

      .mult-btn {
        display: flex;

        button {
          flex: 1;
        }
      }

    }
  }

  .ts-part {
    position: relative;

    .text-tip-block {
      position: absolute;
      top: -88rpx;
      height: 88rpx;
      background: #ffff;
      font-size: 28rpx;
      width: 100%;

      .text-tip {
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #b0b0b0;
        font-size: 28rpx;
      }
    }
  }
</style>
